/* Steve Eisen 
 * CS435 PCAP_MYSQL
 * This program captures packets from a wired network device
 * and logs the headers to a mysql database.
 * The database schema can be found inside schema directory
 * Both the schema and stored procedure need to be implimented before running
 * this program
 * 
 * The README file will explain how to build and run
 * 
 * Currently the capture is focused on TCP packets only
 * 
 */

#include "dstructs.h"


void main(int argc, char **argv)
{
  
  test mytest;
  mytest.conn = mysql_init(NULL);
  int packetCount = atoi(argv[1]); 
  pcap_t* descr; 
  const u_char *packet; 
  char *filename = "pcapfile";
  char *dev, errbuf[PCAP_ERRBUF_SIZE];
  bpf_u_int32 maskp;
  bpf_u_int32 netp;
  
  if(geteuid() != 0)
 {
  fprintf(stderr, "You must be root to run this\n");
  exit(0);
 }

  
  if (mytest.conn == NULL) {
      printf("Error %u: %s\n", mysql_errno(mytest.conn), mysql_error(mytest.conn));
      exit(1);
  }
  
  if (mysql_real_connect(mytest.conn, "localhost", "root", 
          "pass", "ids_db", 0, NULL, 0) == NULL) {
      printf("Error %u: %s\n", mysql_errno(mytest.conn), mysql_error(mytest.conn));
      exit(1);
  }
  if(!(dev = pcap_lookupdev(errbuf))){
        fprintf(stderr, "%s\n", errbuf);
        exit(1);
  }//end if
  pcap_lookupnet(dev, &netp, &maskp, errbuf);
  
  if(!(descr = pcap_open_live(dev, BUFSIZ, 1,-1, errbuf))){
        exit(1);
  }//end if
  
  
  if(!(mytest.dumpfile=pcap_dump_open(descr,filename)))
    printf("error");
  
  pcap_loop(descr,packetCount, pcap_callback,(u_char *)&mytest);
}//end main
